﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Esb.Domain.DomainObjects;
using Esb.Domain.DTO;

namespace Esb.Domain.Factories
{
    /// <summary>
    /// 服务工厂
    /// </summary>
    public class ServiceFactory : FactoryBase<ServiceDo, int>
    {
        public ServiceFactory() : base("Esb") 
        {

        }

        /// <summary>
        /// 根据AppcationId获取Service
        /// </summary>
        /// <param name="appId"></param>
        /// <returns></returns>
        public ServiceDo GetServiceByApplicationId(int applicationId)
        {
            Func<ServiceDo, bool> queryCondition = (ServiceDo svc) => {
                return svc.ApplicationId == applicationId;
            };

            IEnumerable<ServiceDo> result = Repository.FindBySpecification(queryCondition);
            return result.FirstOrDefault();
        }

        /// <summary>
        /// 根据服务名获得服务
        /// </summary>
        /// <param name="Service"></param>
        /// <returns></returns>
        public ServiceDo GetServiceByServiceName(string serviceName)
        {
            Func<ServiceDo, bool> queryCondition = (ServiceDo svc) =>
            {
                return svc.ServiceRouteName == serviceName;
            };

            IEnumerable<ServiceDo> result = Repository.FindBySpecification(queryCondition);
            return result.FirstOrDefault();
        }

        /// <summary>
        /// 服务是否已经注册
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="serviceUrl"></param>
        /// <returns></returns>
        public bool IsRegistered(int applicationId, string serviceName)
        {
            Func<ServiceDo, bool> queryCondition = (ServiceDo svc) =>
            {
                return svc.ServiceRouteName == serviceName && svc.ApplicationId == applicationId;
            };

            IEnumerable<ServiceDo> result = Repository.FindBySpecification(queryCondition);
            return result.Count() > 0;
        }

        /// <summary>
        /// 根据条件查询服务
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public List<ServiceDo> GetServicesByCondition(QueryCondition condition)
        {
            //TODO:问题，过滤条件可能为空
            Func<ServiceDo, bool> queryCondition = (ServiceDo svc) =>
            {
                return svc.ServiceRouteName == condition.ServiceName &&
                    svc.ServiceDescription == condition.ServiceDescription &&
                    svc.Id == condition.Id &&
                    svc.ApplicationId == condition.ApplicationId;
            };

            IEnumerable<ServiceDo> result = Repository.FindBySpecification(queryCondition);
            return result.ToList();
        }
    }
}
